package com.uplooking.pms.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.uplooking.pms.common.util.CommonUtil;
import com.uplooking.pms.common.util.Constant;
import com.uplooking.pms.common.vo.DwzPageBean;
import com.uplooking.pms.common.vo.DwzResultBean;

public class LoginInterceptor implements HandlerInterceptor {

	private Logger loger = Logger.getLogger(this.getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession(true);
		// 从session 里面获取用户名的信息
		Object user = session.getAttribute(Constant.SESSION_USER_KEY);
		// 判断如果没有取到用户信息，就跳转到登陆页面，提示用户进行登陆
		if (CommonUtil.isBlank(user)) {
			loger.info("登录拦截器拦截..." + request.getRequestURI());
			if (isAjax(request)) {
				response.sendRedirect("/toTimeOut");
			} else {
				response.sendRedirect("/toLogin");
			}
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	public static boolean isAjax(HttpServletRequest request) {
		if (request != null && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")))
			return true;
		return false;
	}
}
